import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dictDataApi from '@/api/system/dict-data-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup () {
    const router = useRouter()
    const params = router.currentRoute.value.params
    const dictId = params.id
    console.log(dictId)

    const disabledOptions = [
      { label: '正常', value: false },
      { label: '停用', value: true }
    ]

    const configTypeOptions = [
      { label: '是', value: 'Y' },
      { label: '否', value: 'N' }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '字典数据',
      api: dictDataApi,
      columns: [
        { prop: 'configName', label: '参数名称', valueType: 'input' },
        { prop: 'configKey', label: '参数键名', valueType: 'input' },
        { prop: 'configValue', label: '参数键值' },
        { prop: 'configType', label: '是否内置', slot: true },
        { prop: 'operation', label: '操作', slot: true }
      ],
      rules: {
        configName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
        configKey: [{ required: true, message: '请输入参数键名', trigger: 'blur' }],
        configValue: [{ required: true, message: '请输入参数键值', trigger: 'blur' }],
        configType: [{ required: true, message: '请选择是否内置', trigger: 'change' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        statusChanged: (row) => {
          const { dictName, disabled } = row
          ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${dictName}"字典数据吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await dictDataApi.save(row)
              if (res.code === 200) {
                ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
              } else {
                row.disabled = !disabled
              }
            })
            .catch(() => {
              row.disabled = !disabled
            })
        }
      }
    }))

    const data = reactive({
      ctx,
      disabledOptions
    })

    // init
    onMounted(() => {
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
